package com.scs.application.modules.fsd.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.scs.application.core.service.BaseServiceImpl;
import com.scs.application.core.utils.StringUtils;
import com.scs.application.modules.fsd.entity.FsdStation;
import com.scs.application.modules.fsd.entity.Humiture;
import com.scs.application.modules.fsd.mapper.HumitureMapper;
import com.scs.application.modules.fsd.mapper.StationMapper;
import com.scs.application.modules.fsd.service.SPDService;
import com.scs.application.modules.fsd.service.StationService;
import com.scs.application.modules.fsd.socket.FsdWebSocketEndpoint;
import com.scs.application.modules.fsd.vo.StorageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 站点管理
 */
@Service
public class StationServiceImpl extends BaseServiceImpl<StationMapper, FsdStation> implements StationService {
    @Autowired
    private SPDService spdService;
    @Autowired
    private HumitureMapper humitureMapper;

    @Override
    public Boolean checkStation(String stationCode) {
        FsdStation station = getOne(new QueryWrapper<FsdStation>().eq("station_code", stationCode));
        if (station == null)
            return false;
        return true;
    }

    @Override
    public List<String> getUserIdByStationCode(String stationCode) {
        return baseMapper.getUserIdByStationCode(stationCode);
    }

    @Override
    public Map<String, Object> getStation(String keyword, Integer currentPage, Integer pageSize) {
        Map<String, Object> map = new HashMap<>();
        map.put("count", this.count(Wrappers.<FsdStation>query().like("station_code", keyword).or().like("station_name", keyword).or().like("station_name_py", keyword)));
        map.put("rows", this.list(
                Wrappers.<FsdStation>query().like("station_code", keyword).or().like("station_name", keyword).or().like("station_name_py", keyword).last("limit " + (currentPage - 1) * pageSize + "," + pageSize).orderByDesc("id")
        ));
        return map;
    }

    @Override
    public boolean updateClient(String stationCode) {
        FsdWebSocketEndpoint fsdWebSocketEndpoint = new FsdWebSocketEndpoint();
        fsdWebSocketEndpoint.sendUpgrade(stationCode);
        return true;
    }

    /**
     * 重启服务时重置智能柜在线状态
     */
    @Override
    public void initOnlineStatus() {
        this.update(Wrappers.<FsdStation>update().set("online_status",false));
    }

    @Override
    public List<Map<String, Object>> getBindStationCode() {
        List<String> StationCode = this.list(Wrappers.<FsdStation>query()).stream().map(FsdStation::getStationCode).collect(Collectors.toList());
        List<StorageResult> storageResults = spdService.getBindStationCode();
        List<String> pname = storageResults.stream().map(StorageResult::getParentStorageName).distinct().collect(Collectors.toList());
        List<Map<String, Object>> bindStationCode = new ArrayList<>();
        pname.forEach(getParentStorageName ->{
            Map<String, Object> opt = new HashMap<>();
            opt.put("label",getParentStorageName);
            List<Map<String,Object>> options = new ArrayList<>();
            storageResults.stream().filter((StorageResult s)->s.getParentStorageName().equals(getParentStorageName)).collect(Collectors.toList()).forEach(StorageResult->{
                Map<String,Object> item = new HashMap<>();
                item.put("label",StorageResult.getStorageName());
                item.put("value",StorageResult.getStorageCode());
                item.put("disabled",StationCode.contains(StorageResult.getStorageCode()));
                options.add(item);
            });
            opt.put("options",options);
            bindStationCode.add(opt);
        });
        return bindStationCode;
    }

    @Override
    public Object getBindStationCodeView() {
        List<String> StationCode = this.list(Wrappers.<FsdStation>query()).stream().map(FsdStation::getStationCode).collect(Collectors.toList());
        List<StorageResult> storageResults = spdService.getBindStationCode();
        List<Map<String,String>> stations= new ArrayList<>();
        storageResults.stream().filter((StorageResult s)->!StationCode.contains(s.getStorageCode())).sorted(Comparator.comparing(StorageResult::getStorageName).reversed()).collect(Collectors.toList()).forEach(StorageResult ->{
            Map<String,String> item = new HashMap<>();
            item.put("stationCode",StorageResult.getStorageCode());
            item.put("stationName",StorageResult.getStorageName());
            item.put("parentStorageName",StorageResult.getParentStorageName());
            stations.add(item);
        });
        return stations;
    }

    @Override
    public Map<String, Object> savehumiture(FsdStation fsdStation)
    {
            if(StringUtils.isNotBlank(fsdStation.getHumiture()))
            {
              //  FsdStation fstorage=baseMapper.selectOne(Wrappers.<FsdStation>query().eq("station_code",fsdStation.getStationCode()));
              //  if(!fstorage.getHumiture().equalsIgnoreCase(fsdStation.getHumiture())) {
                    String errmsg = "";
                    //String Humiture = fsdStation.getHumiture();
                    //String[] Humiturearr = Humiture.split(";");
                    String station_code=fsdStation.getStationCode();
                    if(!StringUtils.isJSONArray(fsdStation.getHumiture())) return  null;
                    JSONArray json = JSONArray.parseArray( fsdStation.getHumiture() );
                   // List<Humiture> fsdHumitureAll=humitureMapper.selectList( new QueryWrapper<Humiture>());//Wrappers.<FsdStation>query()
                    List<Humiture> fsdHumitureAll=humitureMapper.selectList( Wrappers.<Humiture>query());

                    //先重置本柜已记录的
                List<Humiture>  HumiturefBYStation=   fsdHumitureAll.stream().filter((Humiture h)->h.getStationCode().equals(station_code)&&h.getIsSet()==1).collect(Collectors.toList());
                for (Humiture humiture:HumiturefBYStation   ) {
                        humitureMapper.updateById(humiture.setIsSet(0));
                }

                    for(int i=0;i<json.size();i++) {
                        String addr=json.getJSONObject(i).getString("addr");
                        JSONArray jsonProbe=json.getJSONObject(i).getJSONArray("probe");
                        for(int j=0;j<jsonProbe.size();j++)
                        {
                            boolean isSet=jsonProbe.getJSONObject(j).getBoolean("isSet");
                            String remark=jsonProbe.getJSONObject(j).getString("remark");
                            String HumitureNo=j+1 +"";
                            int isSet_int=isSet?1:0;
                            //获取匹配的地址和节点 可能来自其他柜子
                            List<Humiture>  Humiturefilter=   fsdHumitureAll.stream().filter((Humiture h)->h.getHumitureAddr().equals(addr)&&h.getHumitureNo().equals(HumitureNo)).collect(Collectors.toList());
                                if(Humiturefilter.size()>0)//存在先清除其他柜子设置
                                {
                                    Humiture  humiture=Humiturefilter.get(0);
                                    //跳过未使用 或本柜不使用已在其他柜子使用
                                  // if((isSet_int==0&&humiture.getIsSet()==0)||(isSet_int==0&&humiture.getIsSet()!=0&&!humiture.getStationCode().equals(station_code)))continue;
                                    if(isSet_int==0)continue;
                                    humiture.setHumitureRemark(remark);
                                    humiture.setIsSet(isSet_int);
                                    String stationcode=humiture.getStationCode();
                                    if(humiture.getIsSet()==1&&!humiture.getStationCode().equals(station_code))//获取其他柜子已设置 重置
                                    {
                                      FsdStation fsd=  baseMapper.selectOne(Wrappers.<FsdStation>query()
                                                .eq("station_code", stationcode));
                                      if(fsd!=null) {
                                          String HumitureString = reSetHumiture(fsd.getHumiture(), j + 1, addr);
                                          fsd.setHumiture(HumitureString);
                                          baseMapper.updateById(fsd);
                                      }
                                    }
                                    humiture.setStationCode(station_code);
                                    humitureMapper.updateById(humiture);
                                }else//不存在新增
                                {
                                    if(isSet_int==0)continue;
                                    Humiture humiture =new Humiture();
                                    humiture.setHumitureAddr(addr);
                                    humiture.setStationCode(station_code);
                                    humiture.setHumitureNo(HumitureNo);
                                    humiture.setIsSet(isSet_int);
                                    humiture.setHumitureRemark(remark);
                                    humitureMapper.insert(humiture);
                                }
                        }
                    }
            }else
            {
                Map result = new HashMap();
                result.put("success",false);
                result.put("msg", "温湿度数据格式判断异常");
                return  result;
            }

        Map result = new HashMap();
        result.put("success","true");
        result.put("msg", "成功");
        return  result;
                  //  humitureMapper.delete(new Wrapper<Humiture>()).

//                    HashSet<String> hashSet = new HashSet<String>();
//                    for (int i = 0; i < Humiturearr.length; i++) {
//                        hashSet.add(Humiturearr[i]);
//                    }
//                    if (hashSet.size() != Humiturearr.length) {
//                        Map result = new HashMap();
//                        result.put("success", "false");
//                        result.put("msg", "地址重复");
//                        return result;
//                    }
//
//                    List<FsdStation> fsdStations = baseMapper.selectList(Wrappers.<FsdStation>query().ne("station_code", fsdStation.getStationCode()).isNotNull("humiture"));
//                    if (fsdStations.size() > 0) {
//                        for (String Humiture_id : Humiturearr) {
//                            List<String> stationCodelist = fsdStations.stream().filter((FsdStation s) -> s.getHumiture().contains(Humiture_id) && s.getHumiture().length() > 0).map(s -> s.getStationCode()).collect(Collectors.toList());
//                            if (stationCodelist.size() > 0) {
//                                errmsg += "地址" + Humiture_id + "已绑定站点" + String.join(",", stationCodelist) + ";";
//                            }
//                        }
//
//                        if (errmsg.length() > 0) {
//                            Map result = new HashMap();
//                            result.put("success", "false");
//                            result.put("msg", errmsg);
//                            return result;
//                        }
//                    }


            //}


    }

    public  String reSetHumiture(String jsonArr,int no,String addr)
    {
        if(!StringUtils.isJSONArray(jsonArr)) return  jsonArr;

        JSONArray json = JSONArray.parseArray(jsonArr);
        for(int i=0;i<json.size();i++)
            {
                JSONObject a= (JSONObject)json.get(i);
                if(a.getString("addr").equals(addr)) {
                    String probe=a.getString("probe");
                    JSONArray probeArray = JSONArray.parseArray(probe);
                    JSONObject probejson=(JSONObject)probeArray.get(no-1);
                    probejson.put("isSet", false);
                    a.put("probe",probeArray);
                }
            }
        System.out.println("aaaaa"+jsonArr+"|"+json);
        return  json.toJSONString();
    }

}
